#coding=utf-8
import datetime
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from eday import Eday

class Stock(models.Model):
    '''股票'''
    code = models.CharField(max_length=6, unique=True)
    name = models.CharField(max_length=20)
    
    ipo = models.DateField(null=True, blank=True)
    iprice = models.FloatField(null=True, blank=True)
    
    market = models.CharField(max_length=20, null=True, blank=True)
    
    created_on = models.DateField(auto_now_add=True)
    ts_updated_at = models.DateTimeField(null=True, blank=True)
    
    edays = generic.GenericRelation(Eday)
    
    def __unicode__(self):
        return "%s:%s"%(self.name, self.code)
    
    class Meta:
        app_label = 'data'
        
    def get_ts(self):
        if self.tradableshare_set.count() > 0:
            return self.tradableshare_set.order_by('-since')[0].quantity
        return None
    ts = property(fget=get_ts)   
    
    def get_h_ts(self):
        return '%.2f亿股'%(self.ts/100000000.0)
    h_ts = property(fget=get_h_ts)
    
    def get_latest_day(self):
        if self.edays.count() == 0:return None
        return self.edays.order_by('-date')[0]
    latest_day = property(fget=get_latest_day)
    
    def update_ts(self):
        #'''tss: 像 [['2002-04-09', '600000000'],['2002-07-10', '653655400']...]的数据'''
        import stockcrawler
        tss = stockcrawler.get_ts(self.code)['ts']
        
        for ts in tss:
            TradableShare.objects.get_or_create(since=ts[0], quantity=ts[1], stock=self)
        now = datetime.datetime.now()
        self.ts_updated_at = now
        self.save()
        
class TradableShare(models.Model):
   
    stock = models.ForeignKey(Stock)
    since = models.DateField()
    quantity = models.IntegerField()
    
    created_at = models.DateField(auto_now_add=True)
    
    def __unicode__(self):
        return "since %s: %i"%(self.since, self.quantity)
    
    class Meta:
        app_label = 'data'
        
class SIndex(models.Model):
    '''指数'''
    code = models.CharField(max_length=6, unique=True)
    name = models.CharField(max_length=20)
    
    start_on = models.DateField(null=True, blank=True)
    
    created_at = models.DateField(auto_now_add=True)
    
    edays = generic.GenericRelation(Eday)
    
    def __unicode__(self):
        return "%s:%s"%(self.name, self.code)
        
    class Meta:
        app_label = 'data'
